using B.S.NewMedical.Api.Write.Application.Command.User;
using B.S.NewMedical.ErrorCode;
using MediatR;
using Microsoft.AspNetCore.Mvc;
using System.Collections.Generic;

namespace B.S.NewMedical.Api.Write.Controllers
{
    /// <summary>
    /// 用户管理控制器
    /// </summary>
    [Route("api/[controller]")]
    [ApiController]
    public class UserController : ControllerBase
    {
        private readonly IMediator _mediator;

        public UserController(IMediator mediator)
        {
            _mediator = mediator;
        }

        /// <summary>
        /// 创建用户
        /// </summary>
        /// <param name="command">创建用户命令</param>
        /// <returns>创建结果</returns>
        [HttpPost("create")]
        public async Task<ApiResult<int>> CreateUser([FromBody] CreateUserCommand command)
        {
            return await _mediator.Send(command);
        }

        /// <summary>
        /// 获取用户列表
        /// </summary>
        /// <param name="searchKeyword">搜索关键词</param>
        /// <param name="userType">用户类型</param>
        /// <returns>用户列表</returns>
        [HttpGet("list")]
        public async Task<ApiResult<List<UserDto>>> GetUserList([FromQuery] string searchKeyword = "", [FromQuery] string userType = "")
        {
            var command = new GetUserListCommand { SearchKeyword = searchKeyword, UserType = userType };
            return await _mediator.Send(command);
        }

        /// <summary>
        /// 获取权限树
        /// </summary>
        /// <param name="userId">用户ID（可选）</param>
        /// <returns>权限树</returns>
        [HttpGet("permissions/tree")]
        public async Task<ApiResult<List<PermissionTreeDto>>> GetPermissionTree([FromQuery] string userId = "")
        {
            int? userIdInt = null;
            if (!string.IsNullOrEmpty(userId) && int.TryParse(userId, out int parsedUserId))
            {
                userIdInt = parsedUserId;
            }
            
            var command = new GetPermissionTreeCommand { UserId = userIdInt };
            return await _mediator.Send(command);
        }

        /// <summary>
        /// 保存用户权限
        /// </summary>
        /// <param name="request">保存用户权限请求</param>
        /// <returns>保存结果</returns>
        [HttpPost("permissions/save")]
        public async Task<ApiResult<bool>> SaveUserPermissions([FromBody] SaveUserPermissionsRequest request)
        {
            // 验证用户ID
            if (!int.TryParse(request.UserId, out int userId))
            {
                return new ApiResult<bool>
                {
                    Code = ApiEnum.Fail,
                    Msg = "用户ID格式不正确"
                };
            }

            // 转换权限ID列表
            var permissionIds = new List<int>();
            foreach (var permissionIdStr in request.PermissionIds)
            {
                if (int.TryParse(permissionIdStr, out int permissionId))
                {
                    permissionIds.Add(permissionId);
                }
            }

            var command = new SaveUserPermissionsCommand
            {
                UserId = userId,
                PermissionIds = permissionIds
            };

            return await _mediator.Send(command);
        }
    }
} 